package indi.fritz.bigmap.volme.model;

import indi.fritz.bigmap.util.ByteUtil;

public final class KeyValue implements StorageData{
	private static final long serialVersionUID = -7598522740241095238L;
	
	public KeyValue(byte[] key, byte[] value, boolean exist) {
		this.key = key;
		this.value = value;
		this.exist = exist;
	}
	
	private byte[] key;
	private byte[] value;
	private boolean exist;
	
	public byte[] getKey() {
		return key;
	}
	public void setKey(byte[] key) {
		this.key = key;
	}
	public byte[] getValue() {
		return value;
	}
	public void setValue(byte[] value) {
		this.value = value;
	}
	public boolean isExist() {
		return exist;
	}
	public void setExist(boolean exist) {
		this.exist = exist;
	}
	@Override
	public byte[] getByte() {
		byte[] existByte = ByteUtil.booleanToByte(exist);
		byte[] kbs = key;
		byte[] vbs = value;
		byte[] kl = ByteUtil.intToByteArray(kbs.length);
		byte[] vl = ByteUtil.intToByteArray(vbs.length);
		return ByteUtil.merges(new byte[][]{existByte, kl, vl, kbs, vbs});
	}
	
	public static KeyValue format(byte[] bs){
		boolean flag = ByteUtil.byteToBoolean(bs[0]);
		int kl = ByteUtil.byteArrayToInt(ByteUtil.sub(bs, 1, 4));
		int vl = ByteUtil.byteArrayToInt(ByteUtil.sub(bs, 5, 4));
		byte[] key = ByteUtil.sub(bs, 9, kl);
		byte[] value = ByteUtil.sub(bs, kl + 9, vl);
		return new KeyValue(key, value, flag);
	}
	
	@Override
	public String toString() {
		return "{" + ByteUtil.byteArrayToString(key) + ":" + ByteUtil.byteArrayToString(value) +"}";
	}
	public static long existIndex() { return 0; }
}
